﻿#region Usings

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

#endregion

namespace SilverBox.Behaviors
{
    public class MouseDoubleClickBehavior : Behavior<FrameworkElement>
    {
        private bool _esperando;
        private DateTime _esperandoDesde;

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
        protected override void OnAttached()
        {
            AssociatedObject.MouseLeftButtonUp += AssociatedObjectMouseLeftButtonUp;

            base.OnAttached();
        }

        private void AssociatedObjectMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_esperando)
            {
                if (DateTime.Now.Subtract(_esperandoDesde).Milliseconds < 500)
                    OnMouseDoubleClick(e);
                _esperando = false;
            }
            else
            {
                _esperando = true;
                _esperandoDesde = DateTime.Now;
            }
        }

        private void OnMouseDoubleClick(MouseButtonEventArgs args)
        {
            if (MouseDoubleClick != null)
                MouseDoubleClick(AssociatedObject, args);
        }

        public event MouseButtonEventHandler MouseDoubleClick;


        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
        protected override void OnDetaching()
        {
            AssociatedObject.MouseLeftButtonUp -= AssociatedObjectMouseLeftButtonUp;
            base.OnDetaching();
        }
    }
}